import React, { useEffect, useState } from 'react';
import { ProForm, ProFormSelect, ProFormDigit, ProFormUploadButton } from '@ant-design/pro-components';
import { Card, message, Form, Divider } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import api from '../../services/api';
import { Document, KnowledgeBase } from '../../types';

const DocumentForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [initialValues, setInitialValues] = useState<Partial<Document>>();
  const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
  const [chunkingMode, setChunkingMode] = useState<string>('fixed');
  const [form] = Form.useForm();
  const isEdit = !!id;

  useEffect(() => {
    fetchKnowledgeBases();
    if (isEdit) {
      fetchDocument();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  const fetchKnowledgeBases = async () => {
    try {
      const response = await api.get('/knowledge-bases/', { params: { skip: 0, limit: 1000 } });
      const kbData = Array.isArray(response.data) ? response.data : response.data.items || [];
      setKnowledgeBases(kbData);
    } catch (error: any) {
      message.error('Failed to fetch knowledge bases');
      setKnowledgeBases([]);
    }
  };

  const fetchDocument = async () => {
    try {
      const response = await api.get(`/documents/${id}`);
      const docData = response.data;
      setInitialValues(docData);
      setChunkingMode(docData.chunking_mode || 'fixed');
      form.setFieldsValue(docData);
    } catch (error: any) {
      message.error('Failed to fetch document details');
      navigate('/documents');
    }
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const payload = {
        ...values,
        chunking_mode: values.chunking_mode || 'fixed',
      };

      // Remove chunk_size and chunk_overlap if chunking_mode is not 'fixed'
      if (payload.chunking_mode !== 'fixed') {
        delete payload.chunk_size;
        delete payload.chunk_overlap;
      }

      if (isEdit) {
        await api.put(`/documents/${id}`, payload);
        message.success('Document updated successfully');
      } else {
        // For file upload, we need to use FormData
        const formData = new FormData();
        if (values.file && values.file.length > 0) {
          formData.append('file', values.file[0].originFileObj);
        }
        formData.append('knowledge_base_id', payload.knowledge_base_id);
        formData.append('chunking_mode', payload.chunking_mode);
        if (payload.chunk_size) {
          formData.append('chunk_size', payload.chunk_size.toString());
        }
        if (payload.chunk_overlap) {
          formData.append('chunk_overlap', payload.chunk_overlap.toString());
        }

        await api.post('/documents/', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        message.success('Document uploaded successfully');
      }
      navigate('/documents');
    } catch (error: any) {
      message.error(error.response?.data?.detail || `Failed to ${isEdit ? 'update' : 'upload'} document`);
    } finally {
      setLoading(false);
    }
  };

  const handleChunkingModeChange = (value: string) => {
    setChunkingMode(value);
    if (value !== 'fixed') {
      form.setFieldsValue({
        chunk_size: undefined,
        chunk_overlap: undefined,
      });
    } else {
      form.setFieldsValue({
        chunk_size: 1000,
        chunk_overlap: 200,
      });
    }
  };

  const kbOptions = (knowledgeBases || []).map((kb) => ({
    label: kb.name,
    value: kb.id,
  }));

  return (
    <Card title={isEdit ? 'Edit Document' : 'Upload Document'}>
      <ProForm
        form={form}
        initialValues={initialValues || { chunking_mode: 'fixed', chunk_size: 1000, chunk_overlap: 200 }}
        onFinish={handleSubmit}
        loading={loading}
        submitter={{
          searchConfig: {
            submitText: isEdit ? 'Update' : 'Upload',
          },
          resetButtonProps: {
            onClick: () => navigate('/documents'),
          },
        }}
      >
        <ProFormSelect
          name="knowledge_base_id"
          label="Knowledge Base"
          options={kbOptions}
          placeholder="Select knowledge base"
          rules={[{ required: true, message: 'Please select a knowledge base' }]}
          fieldProps={{
            showSearch: true,
            filterOption: (input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
          }}
        />

        {!isEdit && (
          <ProFormUploadButton
            name="file"
            label="File"
            max={1}
            fieldProps={{
              accept: '.pdf,.txt,.doc,.docx,.md',
              listType: 'text',
            }}
            rules={[{ required: true, message: 'Please select a file to upload' }]}
            extra="Supported formats: PDF, TXT, DOC, DOCX, MD"
          />
        )}

        <Divider>Chunking Configuration</Divider>

        <ProFormSelect
          name="chunking_mode"
          label="Chunking Mode"
          options={[
            { label: 'Fixed Size', value: 'fixed' },
            { label: 'Semantic', value: 'semantic' },
            { label: 'Paragraph', value: 'paragraph' },
            { label: 'None', value: 'none' },
          ]}
          placeholder="Select chunking mode"
          rules={[{ required: true, message: 'Please select chunking mode' }]}
          fieldProps={{
            onChange: handleChunkingModeChange,
          }}
          tooltip="Fixed: Split by character count; Semantic: Split by meaning; Paragraph: Split by paragraphs; None: No chunking"
        />

        {chunkingMode === 'fixed' && (
          <>
            <ProFormDigit
              name="chunk_size"
              label="Chunk Size"
              placeholder="Enter chunk size (characters)"
              min={100}
              max={10000}
              rules={[{ required: true, message: 'Please enter chunk size' }]}
              tooltip="Number of characters per chunk"
            />

            <ProFormDigit
              name="chunk_overlap"
              label="Chunk Overlap"
              placeholder="Enter chunk overlap (characters)"
              min={0}
              max={1000}
              rules={[{ required: true, message: 'Please enter chunk overlap' }]}
              tooltip="Number of overlapping characters between chunks"
            />
          </>
        )}
      </ProForm>
    </Card>
  );
};

export default DocumentForm;
